
function getCityId() {
  var cityName = document.getElementById('cityInput').value;
  var url = 'https://geoapi.qweather.com/v2/city/lookup?location=' + encodeURIComponent(cityName) + '&key=713a27bbf35b42faab1b792c2d1d7bcf';
  var request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.onload = function () {
    if (request.status >= 200 && request.status < 400) {
      var response = JSON.parse(request.responseText);
      if (response.code === '200') {
        var cityId = response.location[0].id;
        getWeather(cityId);
      } else {
        document.getElementById('result').textContent = '找不到该城市，请检查输入是否正确';
      }
    } else {
      document.getElementById('result').textContent = '获取城市信息失败';
    }
  };
  request.onerror = function () {
    document.getElementById('result').textContent = '获取城市信息失败，请检查网络连接或稍后再试';
  };
  request.send();
}

function getWeather(cityId) {
  var url = 'https://devapi.qweather.com/v7/weather/now?location=' + cityId + '&key=713a27bbf35b42faab1b792c2d1d7bcf';
  var request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.onload = function () {
    if (request.status >= 200 && request.status < 400) {
      var response = JSON.parse(request.responseText);
      displayWeather(response);
    } else {
      document.getElementById('result').textContent = '获取天气数据失败';
    }
  };
  request.onerror = function () {
    document.getElementById('result').textContent = '获取天气数据失败，请检查网络连接或稍后再试';
  };
  request.send();
  console.log(request)
}

function displayWeather(weatherData) {
  var weatherText = '当前天气：' + weatherData.now.text;
  var temperatureText = '当前温度：' + weatherData.now.temp + '℃';
  var weatherIconClass = 'qi-' + weatherData.now.icon; // 获取天气图标的 CSS 类名

  // 创建一个 <i> 元素，并添加天气图标的 CSS 类名
  var iconElement = document.createElement('i');
  iconElement.classList.add('weather-icon');
  iconElement.classList.add(weatherIconClass);

  // 创建一个 <div> 元素用于包裹图标和文本内容
  var contentWrapper = document.createElement('div');
  contentWrapper.appendChild(iconElement);

  // 创建 <span> 元素来显示天气文本和温度文本
  var weatherInfoElement = document.createElement('span');
  weatherInfoElement.textContent = weatherText + ', ' + temperatureText;

  // 将天气信息元素添加到内容包裹器中
  contentWrapper.appendChild(weatherInfoElement);

  // 获取结果区域元素
  var resultElement = document.getElementById('result');

  // 清空结果区域原有内容
  resultElement.innerHTML = '';

  // 添加内容包裹器到结果区域
  resultElement.appendChild(contentWrapper);
}

